package aor2.cpu.blockcontrol.horizontal;

import java.util.ArrayList;
import java.util.Iterator;

import aor2.components.ElementIOException;
import aor2.components.Signal;
import aor2.cpu.blockcontrol.ControlSignalSet;
import aor2.cpu.blockcontrol.MicroInstruction;

public class MicroInstructionHorizontal implements MicroInstruction {
	long code;
	ArrayList<Signal> controlSignal;
	ArrayList<String> signals = new ArrayList<String>();

	public MicroInstructionHorizontal(long code) {
		this.code = code;
		this.controlSignal = new ArrayList<Signal>();
	}

	public void addSignal(Signal... signals) {
		for (Signal s : signals) {
			controlSignal.add(s);
		}
	}

	@Override
	public void addSignal(String... signalName) {
		ControlSignalSet css = ControlSignalSet.getInstance();
		for (String s : signalName) {
			controlSignal.add(css.get(s));
		}
	}

	public void addSignal(String signalName) {
		ControlSignalSet css = ControlSignalSet.getInstance();
		signals.add(signalName);
		controlSignal.add(css.get(signalName));
		// System.out.println(signalName);
	}

	@Override
	public void start() {
		if (controlSignal == null)
			return;
		Iterator<Signal> iterS = controlSignal.iterator();
		while (iterS.hasNext()) {
			iterS.next().setActive(true);
		}
		iterS = controlSignal.iterator();
		while (iterS.hasNext()) {
			try {
				iterS.next().out();// na svim source poziva out!!! CHANGE
			} catch (ElementIOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void updateStates() {
		if (controlSignal == null)
			return;
		Iterator<Signal> iterS = controlSignal.iterator();
		while (iterS.hasNext()) {
			try {
				iterS.next().in();// na destinacionim CHANGE
			} catch (ElementIOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void clearSignals() {
		if (controlSignal == null)
			return;
		Iterator<Signal> iterS = controlSignal.iterator();
		while (iterS.hasNext()) {
			iterS.next().setActive(false);
		}
		// InternBus.clear();
	}

	@Override
	public String toString() {
		return "" + signals;
	}

	@Override
	public long getCode() {
		return code;
	}

}
